// Copyright (c) 2013 Inkling Systems, Inc. All rights reserved.
package com.inkling.imagesearch;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;

public class MainActivity extends Activity{
	
	private GridView gridview;
	private GridViewImageAdapter gridViewAdapter;
	private ProgressDialog dialog;
	private ArrayList<Object> listImages;
	private int pageCounter=1;
	private boolean isLoading = true;
	
	private final String errorMsg="Something went wrong";
	private final String noMoreResultMsg = "No more result";

	 
	@SuppressLint("HandlerLeak")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		 
		setContentView(R.layout.activity_main);
		
		final EditText searchText = (EditText) findViewById(R.id.search_text);		
		final Button searchButton = (Button) findViewById(R.id.search_button);
		final Button showMoreButton = (Button) findViewById(R.id.showmore_button);
		
		showMoreButton.setVisibility(View.GONE);
		
		//gridview
		gridview = (GridView) findViewById(R.id.image_gridView);
		
	
		//add listener to the gridview, for showing the more result button
		gridview.setOnScrollListener(new OnScrollListener(){
			@Override
			public void onScroll(AbsListView arg0, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				 Log.d("h2", "firstVisibleItem::" + firstVisibleItem + "::" + visibleItemCount + "::" + totalItemCount);
				 Log.d("h2", "count::" + (totalItemCount - firstVisibleItem));
				 
				 
				  if (!isLoading && (totalItemCount - firstVisibleItem) <= visibleItemCount) {		                
						showMoreButton.setVisibility(View.VISIBLE);	
				  }
				  else
					  showMoreButton.setVisibility(View.GONE);
			}

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				Log.d("h2", "onScroll state change");
			}
		});
		
		//callback handler, to know if loading is finish
		final Handler notifyHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
		
				//something went wrong with google search
				if(msg.what==-1)
					showDialogMsg(errorMsg);
					
				gridViewAdapter = new GridViewImageAdapter(MainActivity.this, listImages);
				gridview.setAdapter(gridViewAdapter);
				
				isLoading = false;
				
				if(pageCounter>1)
					gridview.setSelection(gridview.getCount());
	
				pageCounter ++;
				dialog.dismiss();
				
			}
		};
		
		searchButton.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				
				listImages = new ArrayList<Object>();
				
				// TODO: Soft keyboard may remain on screen when Search is tapped
				// Can we do something about it?
				//hide the soft keyboard after pressing search
				InputMethodManager imm = (InputMethodManager)getSystemService(
					      Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(searchText.getWindowToken(), 0);
				
				// Create an asynchronous search task
				String keyword = searchText.getText().toString();
				if(keyword.length()!=0){
				   dialog = ProgressDialog.show(MainActivity.this, "", "Please wait...");
				   pageCounter=1;
				   new SearchTask(notifyHandler, listImages, pageCounter * 15).execute(keyword);
				  
				}

			}
		});
		
		//listener for showMoreButton
		showMoreButton.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				Log.d("h2", "pageCounter::" + pageCounter);
				if(pageCounter > 4){
					showDialogMsg(noMoreResultMsg);
				}
				else{
				 String keyword = searchText.getText().toString();
				 if(keyword.length()!=0){
				   dialog = ProgressDialog.show(MainActivity.this, "", "Please wait...");
				   new SearchTask(notifyHandler, listImages, pageCounter * 15).execute(keyword);
				   
				   
				 }
				}
		
			}
		});
		
		
		//hides the show more button when edit text is highlight, for UI design purposes
		searchText.setOnClickListener(new View.OnClickListener() {
	        @Override
	        public void onClick(View v) {
	        	showMoreButton.setVisibility(View.GONE);
	        }
	    });
		
		
		
		
	
		
	}
	
	public void showDialogMsg(String msg){

		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setMessage(msg)
				.setPositiveButton("ok", new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	               
	           }
	    });

		AlertDialog dialog = builder.create();
		dialog.show();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}



}
